import uuid
from django.shortcuts import render, HttpResponse, redirect
from book import froms
from book import models
from django.http import JsonResponse
from django.contrib import auth
from PIL import Image, ImageDraw, ImageFont
from io import BytesIO  # 内存句柄
from book.utils.page import Pagination
from django.db.models import Q, F


# Create your views here.


def reg(request):
    if request.method == "POST":
        res = {"user": None, "error": ""}
        form = froms.Reg(request.POST)
        if form.is_valid():
            res["user"] = form.cleaned_data.get("username")
            form.cleaned_data.pop('var_pwd')  # 把多余的字段删掉
            models.User.objects.create_user(**form.cleaned_data)  # 批量加进去，form.cleaned_data里字段名要和数据库的字段名一致
        else:
            res["error"] = form.errors
        return JsonResponse(res)  # 可以自动转成json
    else:
        form = froms.Reg()
        return render(request, 'login/reg.html', locals())


def login(request):
    if request.is_ajax():
        username = request.POST.get('username')
        password = request.POST.get('password')
        code = request.POST.get('code')
        print(username, password, code, request.session.get("code_str"))
        res = {"username": None, "error": "", "code": ""}
        if code.lower() == request.session.get("code_str").lower():
            user_res = auth.authenticate(username=username, password=password)
            if user_res:
                auth.login(request, user_res)
                res["username"] = username
            else:
                res["error"] = "账号或密码错误!"
        else:
            res["code"] = "验证码错误!"
        return JsonResponse(res)
    else:
        form = froms.Login()
        return render(request, "login/login.html", locals())


# 注销
def logout(request):
    auth.logout(request)
    return redirect("/login/")


# 验证码
def get_code_img(request):
    import random
    width = 150
    height = 48
    code_str = ''

    def random_color():
        return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))

    img = Image.new("RGB", (150, 48), (255, 255, 255))
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("static/fonts/kumo.ttf", 32)

    for i in range(5):
        number = str(random.randrange(10))
        upper = chr(random.randrange(65, 91))
        lower = chr(random.randrange(97, 123))
        char = random.choice([number, upper, lower])
        draw.text((i * 25 + 20, 7), char, random_color(), font=font)
        code_str += char

    for i in range(5):
        x1 = random.randint(0, width)
        x2 = random.randint(0, width)
        y1 = random.randint(0, height)
        y2 = random.randint(0, height)
        draw.line((x1, y1, x2, y2), fill=random_color())

    for i in range(10):
        draw.point([random.randint(0, width), random.randint(0, height)], fill=random_color())
        x = random.randint(0, width)
        y = random.randint(0, height)
        draw.arc((x, y, x + 4, y + 4), 0, 90, fill=random_color())
    fio = BytesIO()
    img.save(fio, 'png')
    data = fio.getvalue()
    request.session["code_str"] = code_str  # 把验证码存到session里
    return HttpResponse(data)


def index(request):
    book = models.Book.objects.all()
    # 条件过滤
    var = request.GET.get("q")
    if var:
        book = book.filter(Q(title__contains=var))
    # 符合条件返回符合条件的数据，否则就返回所有然后分页
    page_num = request.GET.get("page")
    pagination = Pagination(page_num, book.count(), request)
    book_page = book[pagination.start:pagination.end]  # 分好页的数据
    return render(request, "book/index.html", {"book": book_page, "pagination": pagination})


def add_book(request):
    if request.method == "GET":
        book = froms.Book()
        return render(request, "book/add_book.html", {"book": book})
    else:
        book = froms.Book(request.POST)
        if book.is_valid():
            authors = book.cleaned_data.pop("authors")
            books = models.Book.objects.create(**book.cleaned_data)
            books.authors.add(*authors)
            return redirect("/index/")
        else:
            return render(request, "book/add_book.html", {"book": book})


def del_book(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Book.objects.get(id=drop_id)
    drop_obj.delete()
    return redirect('/index/')


def edit_book(request, edit_id):
    edit_obj = models.Book.objects.get(pk=edit_id)
    if request.method == "POST":
        form = froms.EditBook(instance=edit_obj, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("/index/")
    else:
        form = froms.EditBook(instance=edit_obj)
    return render(request, "book/edit_book.html", {"book": form})


# 作者管理
def view_author(request):
    authors = models.Author.objects.all()
    # 符合条件返回符合条件的数据，否则就返回所有然后分页
    page_num = request.GET.get("page")
    pagination = Pagination(page_num, authors.count(), request)
    author_list = authors[pagination.start:pagination.end]  # 分好页的数据
    return render(request, "book/view_author.html", {"authors": author_list, "pagination": pagination})


def add_author(request):
    if request.method == "GET":
        author = froms.AddAuthor()
        return render(request, "book/add_author.html", {"author": author})
    else:
        author = froms.AddAuthor(request.POST)
        if author.is_valid():
            author_detail = author.cleaned_data.pop("name")
            author_id = models.AuthorDetail.objects.create(**author.cleaned_data)
            models.Author.objects.create(name=author_detail, author_detail=author_id)
            return redirect("/view_author/")
        else:
            return render(request, "book/add_author.html", {"author": author})


def edit_author(request, author_id):
    edit_obj = models.Author.objects.get(pk=author_id)
    detail = models.AuthorDetail.objects.get(pk=edit_obj.author_detail_id)
    if request.method == "POST":
        form = froms.EditAuthor(instance=edit_obj, data=request.POST)
        author_detail = froms.AuthorDetail(instance=detail, data=request.POST)
        if form.is_valid() and author_detail.is_valid():
            form.save()
            author_detail.save()
            return redirect("/view_author/")
    else:
        form = froms.EditAuthor(instance=edit_obj)
        author_detail = froms.AuthorDetail(instance=detail)
    return render(request, "book/edit_author.html", {"author": form, "author_detail": author_detail})


def del_author(request):
    drop_id = request.GET.get('id')
    drop_obj = models.Author.objects.get(pk=drop_id)
    detail = models.AuthorDetail.objects.get(pk=drop_obj.author_detail_id)
    drop_obj.delete()
    detail.delete()
    return redirect('/view_author/')


def view_publish(request):
    publish_list = models.Publish.objects.all()
    # 符合条件返回符合条件的数据，否则就返回所有然后分页
    page_num = request.GET.get("page")
    pagination = Pagination(page_num, publish_list.count(), request)
    publish_page = publish_list[pagination.start:pagination.end]  # 分好页的数据
    return render(request, "book/view_publish.html", {"publish_list": publish_page, "pagination": pagination})


def add_publish(request):
    if request.method == "POST":
        publish_list = froms.Publish(request.POST)
        if publish_list.is_valid():
            models.Publish.objects.create(**publish_list.cleaned_data)
            return redirect("/view_publish/")
    publish = froms.Publish()
    return render(request, "book/add_publish.html", {"publish": publish})


def edit_publish(request, publish_id):
    res = models.Publish.objects.get(pk=publish_id)
    if request.method == "POST":
        form = froms.Publish(instance=res, data=request.POST)
        if form.is_valid():
            form.save()
            return redirect("/view_publish/")
    publish = froms.Publish(instance=res)
    return render(request, "book/edit_publish.html", {"publish": publish})


def del_publish(request):
    drop_id = request.GET.get('id')
    detail = models.Publish.objects.get(pk=drop_id)
    detail.delete()
    return redirect('/view_publish/')
